import 'dart:io';

import 'package:hrf_app/common/api/bug/bug.dart';
import 'package:hrf_app/common/api/file_upload/file_upload.dart';
import 'package:hrf_app/common/api/material/material.dart';
import 'package:hrf_app/common/models/bug/file_model.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/state_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class MaterialAddPageController extends GetxController {
  MaterialAddPageController();

  TextEditingController nameController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  TextEditingController remarkController = TextEditingController();
  List<UploadFileModel> uploadFileModelList = [];
  Map saveMap = {};

  _initData() {
    update(["MaterialAddPage"]);
  }

  void onTap() {}

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  Future<void> selectPhoto(ImageSource source) async {
    List<File> images = [];
    final picker = ImagePicker();
    final XFile? pickedFile = await picker.pickImage(source: source);
    if (pickedFile != null) {
      images.add(File(pickedFile.path));
    }
    uploadImg(images);
  }

  Future<void> selectMultiImage() async {
    List<File> images = [];
    final picker = ImagePicker();
    final List<XFile> pickedFileList = await picker.pickMultiImage();
    List<File> imageList = [];
    if (pickedFileList != null) {
      imageList = pickedFileList.map((file) => File(file.path)).toList();
    }
    images.addAll(imageList);
    uploadImg(images);
  }

  Future<void> uploadImg(List<File> imgList) async {
    // 单个文件上传
    List<MultipartFile> multipartFile = [];
    for (var element in imgList) {
      // 压缩图片
      var result = await FlutterImageCompress.compressWithFile(
          element.absolute.path,
          minHeight: 1600,
          minWidth: 1600);
      // 将压缩后的图片保存到临时文件
      var compressedFile = File("${element.path}_compressed.jpg")
        ..writeAsBytesSync(result!);
      // 将压缩后的文件转换为 MultipartFile
      MultipartFile mfile = await MultipartFile.fromFile(
        compressedFile.path,
      );
      multipartFile.add(mfile);
    }
    FormData formData = FormData.fromMap(
        {'fileList': multipartFile, "fileFirstName": "material"});
    UploadApi.simpleUploadListApi(formData).then((res) {
      if (res["code"] == "00000") {
        List<dynamic> imgUrlMap = res['data'];
        for (var itemVo in imgUrlMap) {
          UploadFileModel uploadFileModel = UploadFileModel();
          uploadFileModel.url =  itemVo["url"];

          uploadFileModelList.add(uploadFileModel);
        }
        TDToast.showSuccess("上传成功", context: Get.context!);
        update(["MaterialAddPage"]);
      }
    });
  }

  save() {
    String name = nameController.text;
    String code = codeController.text;
    String remark = remarkController.text;
    saveMap['name'] = name;
    saveMap['code'] = code;
    saveMap['remark'] = remark;
    if(name==null||name==""){
      TDToast.showWarning("请输入名称", context: Get.context!);
      return;
    }
    saveMap['materialFileVoList'] = uploadFileModelList;
    print(saveMap.toString());

    MaterialApi.addMaterialApi(saveMap).then((res) {
      if (res["code"] == "00000") {
        Get.toNamed(RouteNames.materialAddPage);
      }
    });
  }

  void delImage(index) {
    if (index >= 0 && index < uploadFileModelList.length) {
      uploadFileModelList.removeAt(index);
      update(["MaterialAddPage"]);
    }
  }
}
